/**
 * 
 */
package com.ihome.framework.core.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;

import com.ihome.framework.core.lock.DistributedLockBuilder.Factory;

/**
 * @author zww
 *
 */
public class HomeMultiDistributedLockImpl implements IHomeMultiDistributedLock{


    private final Map<String, IHomeDistributedLock> LOCK_MAP = new ConcurrentHashMap<String, IHomeDistributedLock>();

    private final Factory factory;
    private final Object client;
    public HomeMultiDistributedLockImpl(Factory factory,Object client){
        this.factory = factory;
        this.client = client;
    }


    /* (non-Javadoc)
     * @see com.ihome.framework.core.lock.IHomeMultiDistributedLock#tryLock(java.lang.String, int, int,java.util.concurrent.TimeUnit)
     */
    @Override
    public boolean tryLock(String lockName,int waitTimeOut,int lockTimeOut,TimeUnit unit) {
        if(!LOCK_MAP.containsKey(lockName)){
            LOCK_MAP.put(lockName, new DistributedLockBuilder().client(client).exp(lockTimeOut, unit).lockName(lockName).factory(factory).client(client).build());
        }

        IHomeDistributedLock distributedLock = LOCK_MAP.get(lockName);
        return distributedLock.ping() && distributedLock.tryLock(waitTimeOut, unit);
    }

    /* (non-Javadoc)
     * @see com.ihome.framework.core.lock.IHomeMultiDistributedLock#unlock()
     */
    @Override
    public boolean unlock() {
        final ConcurrentMap<String, IHomeDistributedLock> tempHashMap = new ConcurrentHashMap<String, IHomeDistributedLock>(LOCK_MAP);
        for (String key : tempHashMap.keySet()) {
            if(tempHashMap.get(key).unlock()){
                LOCK_MAP.remove(key);
            }
        }
        return LOCK_MAP.isEmpty();
    }

    /* (non-Javadoc)
     * @see org.springframework.beans.factory.DisposableBean#destroy()
     */
    @Override
    public void destroy() throws Exception {
        for (IHomeDistributedLock distributedLock : LOCK_MAP.values()) {
            distributedLock.destroy();
        } 
    }

}
